package com.tange.ai.iot.client.gnssa.service

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityOrderListBinding
import com.tange.ai.iot.client.gnssa.message.MessageSettingActivity
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.cloud.message.*
import com.tange.core.value.added.service.Order
import com.tange.core.value.added.service.ValueAddedService


/**
 * 设备的订单信息
 */
class ValueAddedOrderActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "ValueAddedOrderActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, ValueAddedOrderActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var binding: ActivityOrderListBinding
    private lateinit var listAdapter: ListAdapter
    private lateinit var deviceId: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        binding = ActivityOrderListBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
            top.title.text = "订单列表"
        }

        binding.top.left.onClicked { finish() }
        binding.top.right.onClicked { MessageSettingActivity.launch(it.context, deviceId) }

        listAdapter = ListAdapter()
        binding.serviceList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.serviceList.adapter = listAdapter

        queryDeviceService()
    }

    private fun queryDeviceService() {

        binding.loading.visible()
        binding.emptyView.gone()


        ValueAddedService.queryOrdersList(deviceId) {
            binding.loading.gone()
            if (it.success) {
                it.data?.let {
                    if ((it.items?.size?:0) <= 0) {
                        binding.emptyView.visible()
                        binding.serviceList.gone()
                    } else {
                        it.items?.let {
                            listAdapter.refresh(it)
                        }
                        binding.emptyView.gone()
                        binding.serviceList.visible()
                    }
                }
            } else {
                Tips.show("请求失败：${it.code}, ${it.message}")
            }
        }
    }

    inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        private val orders: MutableList<Order> = java.util.ArrayList()

        fun refresh(list: List<Order>) {
            orders.clear()
            orders.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.item_service_list, viewGroup, false)
            return ViewHolderMessage(view)
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

            if (holder is ViewHolderMessage) {
                val viewHolderMessage: ViewHolderMessage = holder
                val item = orders[position]

                if ((item.amount ?: 0.0) > 0) {
                    viewHolderMessage.name.text = "${item.amount} ${item.currencyCode}"
                } else {
                    viewHolderMessage.name.text = "无金额信息"
                }

                viewHolderMessage.icon.background = ContextCompat.getDrawable(viewHolderMessage.icon.context, R.drawable.baseline_attach_money_24)
                viewHolderMessage.start.text = "创建时间：${((item.createAt ?: 0) * 1000L).asTime()}"

                when (item.status) {
                    0 -> viewHolderMessage.end.text = "待支付"
                    1 -> viewHolderMessage.end.text = "支付处理中"
                    2 -> viewHolderMessage.end.text = "支付完成"
                    3 -> viewHolderMessage.end.text = "支付失败"
                    4 -> viewHolderMessage.end.text = "退款中"
                    5 -> viewHolderMessage.end.text = "退款失败"
                    6 -> viewHolderMessage.end.text = "已退款"
                    else -> viewHolderMessage.end.text = "支付状态未知"
                }

                viewHolderMessage.itemView.onClicked {
                    BasicDialogRequest(it.context).apply {
                        setMessage("订单详情：\n${item.toString()}")
                        setPositiveText("好")
                        setPositiveOnClicked {
                            dismiss()
                        }
                    }.show()
                }

            }
        }

        override fun getItemCount(): Int = orders.size
    }

    class ViewHolderMessage(view: View) : RecyclerView.ViewHolder(view) {
        val name: TextView
        val start: TextView
        val end: TextView
        val icon: ImageView

        init {
            icon = view.findViewById(R.id.category_icon)
            name = view.findViewById(R.id.name)
            start = view.findViewById(R.id.start)
            end = view.findViewById(R.id.end)

        }
    }
}